package com.xhwl.data.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import com.xhwl.common.dto.auth.AuthenticationDTO;
import com.xhwl.common.dto.cent.sdata.*;
import com.xhwl.common.enums.AppTypeEnum;
import com.xhwl.common.enums.CodeEnum;
import com.xhwl.common.enums.LoginTypeEnum;
import com.xhwl.common.enums.PasswordEditEnum;
import com.xhwl.common.enums.config.BusinessType;
import com.xhwl.common.enums.config.RoleTypeEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.exception.DataException;
import com.xhwl.common.pojo.AbstractAccount;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.*;
import com.xhwl.common.pojo.cent.sdata.devplatform.Developer;
import com.xhwl.common.pojo.cent.sdata.personnel.StaffDTO;
import com.xhwl.common.query.cent.sdata.*;
import com.xhwl.common.query.cent.sdata.AccountQuery;
import com.xhwl.common.query.cent.sdata.AccountRoleQuery;
import com.xhwl.common.query.cent.sdata.EnterpriseQuery;
import com.xhwl.common.query.cent.sdata.ProjectQuery;
import com.xhwl.common.query.cent.sdata.RoleQuery;
import com.xhwl.common.utils.CentDataVerifyUtil;
import com.xhwl.common.utils.ChkUtil;
import com.xhwl.common.utils.DataVerifyUtil;
import com.xhwl.common.vo.cent.sdata.AccountDetailVO;
import com.xhwl.common.vo.cent.sdata.AccountSearchVO;
import com.xhwl.data.config.PwdConfig;
import com.xhwl.data.pojo.AccountOperatorAuth;
import com.xhwl.data.pojo.AccountQueryVO;
import com.xhwl.data.service.*;
import com.xhwl.data.service.devplatform.IDeveloperService;
import com.xhwl.data.service.personal.IStaffService;
import com.xhwl.data.util.ValidatorUtil;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: JCccc
 * @Description:
 * @Date: Create in 15:17 2021/1/14
 */
@RestController
public class AccountController {
    private static final Logger log = LoggerFactory.getLogger(AccountController.class);
    @Autowired
    IAccountService accountService;
    @Autowired
    IRoleService roleService;
    @Autowired
    IAccountOpenAuthService accountOpenAuthService;
    @Autowired
    IEnterpriseService enterpriseService;
    @Autowired
    IAccountRoleService accountRoleService;
    @Autowired
    IProjectService projectService;
    @Autowired
    IAccountProjectService accountProjectService;
    @Autowired
    IMessageCodeService messageCodeService;
    @Autowired
    private IAppService appService;
    @Autowired
    private IAdminAccountService adminAccountService;

    @Autowired
    private IDeveloperService developerService;

    @Autowired
    private IPermissionGroupService permissionGroupService;

    @Autowired
    private PwdConfig pwdConfig;

    @Autowired
    IBuildingService buildingService;
    @Autowired
    private IStaffService staffService;
    @Autowired
    private IOrganizationService organizationService;

    /**
     * 根据角色分组查询账号
     *
     * @param industryId
     * @return
     */
    @GetMapping(value = "/account/group-by-role")
    public ResultJson groupByRolePage(@RequestHeader(value = "industryId", required = true) Short industryId,
                                      AccountRoleQuery accountRoleQuery) {

        List<Integer> proIds = accountRoleQuery.getProjectIdList();
        if (CollectionUtils.isEmpty(proIds)) {
            return ResultJson.fail("缺少项目数据");
        }
        accountRoleQuery.setIndustryId(industryId);
        return accountService.listGroupByRole(accountRoleQuery);
    }


    /**
     * 查询-动态条件  （分页）
     *
     * @param page
     * @param accountSearch
     * @return
     */
    @GetMapping(value = "/account/page-list")
    public ResultJson pageList(@RequestHeader(value = "industryId", required = false) Short industryId, Account operateAccount, Page page, AccountSearchVO accountSearch) {
        //设置默认搜索的排序条件
        setDefaultSearchOrder(page);
        //转化搜索条件
        AccountQuery accountQuery = convertDynamicAccountQuery(industryId, accountSearch, operateAccount);
        //账号信息获取
        Page<AccountDTO> accountPageList = accountService.getPageList(page, accountQuery);
        return ResultJson.success(accountPageList);
    }

    /**
     * 分页查询
     *
     * @param accountQueryVO
     * @return
     */
    @PostMapping("/account/page")
    public ResultJson page(@RequestBody AccountQueryVO accountQueryVO, Account account, Developer developer) {
        Page<AccountDTO> accountPageList = accountService.page(accountQueryVO.getAccountQuery().setDevelopId(developer.getId()), accountQueryVO.getPage());
        return ResultJson.success(accountPageList);
    }

    /**
     * 根据业态角色查询帐号
     * @param accountQueryVO
     * @param industryId
     * @return
     */
    @PostMapping("/account/industry-role/page")
    public ResultJson page(@RequestBody AccountQueryVO accountQueryVO,
                           @RequestHeader Integer industryId, Developer developer) {
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.select("id");
        roleQueryWrapper.eq("is_deleted", false);
        roleQueryWrapper.eq("industry_id", industryId);
        // 只查询业态角色
        roleQueryWrapper.eq("grade", 2);
        List<Role> list = roleService.list(roleQueryWrapper);
        if(list.isEmpty()){
            return ResultJson.fail("请先创建角色");
        }
        List<Integer> collect = list.stream().map(i -> i.getId()).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(accountQueryVO.getAccountQuery().getRoleIdList())){
            accountQueryVO.getAccountQuery().setRoleIdList(collect);
        }
        accountQueryVO.getAccountQuery().setDevelopId(developer.getId());
        Page<AccountDTO> accountPageList = accountService.page(accountQueryVO.getAccountQuery(), accountQueryVO.getPage());

        // 过滤其他平台的角色，只显示当前平台的角色信息
        List<AccountDTO> records = accountPageList.getRecords();
        for (AccountDTO record : records) {
            List<Integer> roleFilter = new ArrayList<>();
            List<String> roleNameFilter = new ArrayList<>();
            for (Role r : record.getRoles()) {
                if(collect.contains(r.getId())){
                    roleFilter.add(r.getId());
                    roleNameFilter.add(r.getName());
                }
            }
            record.setRoleIds(roleFilter);
            record.setRoleNames(roleNameFilter);
        }

        return ResultJson.success(accountPageList);
    }


    /**
     * 查询-动态条件 （不分页）
     *
     * @param accountSearch
     * @return
     */
    @GetMapping(value = "/account/list")
    public ResultJson list(
            @RequestHeader(value = "industryId", required = true) Short industryId,
            AccountSearchVO accountSearch,
            Account operateAccount) {
        AccountQuery accountQuery = convertDynamicAccountQuery(industryId, accountSearch, operateAccount);
        //账号信息获取
        List<AccountDTO> accountList = accountService.getList(accountQuery);
        return ResultJson.success(accountList);
    }

    /**
     * 根据角色id获取账号信息 工作流用
     * @param industryId
     * @param roleIds
     * @return
     */
    @GetMapping(value = "account/list-by-roleId")
    public ResultJson list(
            @RequestHeader(value = "industryId", required = true) Short industryId,
            @RequestParam(value = "roleIds") List<Integer> roleIds) {
        List<AccountDTO> accountList = accountService.getListByRoleIds(roleIds);
        return ResultJson.success(accountList);
    }

    /**
     * 根据id获取账号详情
     *
     * @param account
     * @param industryId
     * @param id
     * @return
     */
    @GetMapping(value = "/account/detail")
    public ResultJson detail(
            @RequestHeader(value = "industryId", required = true) Short industryId,
            @RequestParam(value = "id", required = false) Integer id, Account account) {
        AccountDetailVO accountDetail = accountService.getDetail(industryId, account, id == null ? account.getId() : id);
        return ResultJson.success(accountDetail);
    }

    @PostMapping(value = "/account/detail/V2")
    public ResultJson detailV2(@RequestBody AccountQuery accountQuery) {
        AccountDetailVO detail = accountService.getDetail(accountQuery);
        return ResultJson.success(detail);
    }

    @PostMapping(value = "/account/detail-by-loginname")
    public ResultJson detailByLoginName(@RequestHeader(value = "appId", required = true) String appId,
                                        @RequestBody AccountQuery accountQuery) {
        App app = appService.getByAppId(appId);
        if (app == null){
            return ResultJson.fail("参数错误");
        }
        accountQuery.setDevelopId(app.getDevelopId());
        AccountDetailVO detail = accountService.getDetail(accountQuery);
        return ResultJson.success(detail);
    }

    /**
     * 账号创建 /修改（应前端要求，采取合并）
     *
     * @param operateAccount
     * @param appId
     * @param industryId
     * @param accountDTO
     * @return
     */
    @PostMapping(value = "/account/create")
    public ResultJson create(Account operateAccount,
                             @RequestHeader(value = "appId", required = true) String appId,
                             @RequestHeader(value = "industryId", required = true) Short industryId,
                             @RequestBody AccountDTO accountDTO, Developer developer) {
        Account account = new Account();
        BeanUtils.copyProperties(accountDTO, account);
        account.setIndustryId(industryId);
        account.setDevelopId(developer.getId());
        if (Objects.isNull(account.getId())) {
            return accountService.createAccount(account, accountDTO.getEnterpriseIds(), accountDTO.getProjectIds(), accountDTO.getRoleIds());
        } else {
            AccountRelation accountRelation = new AccountRelation();
            accountRelation.setEnterpriseIds(accountDTO.getEnterpriseIds());
            accountRelation.setProjectIds(accountDTO.getProjectIds());
            // 只操作当前平台的权限组
            List<Integer> accountRoleIds = new ArrayList<>();
            List<PermissionGroupDTO> permissionGroupDTOList = new ArrayList<>();
            PermissionGroupDTO permissionGroupDTO = new PermissionGroupDTO();
            permissionGroupDTO.setAccountId(account.getId());
            permissionGroupDTO.setRoleList(accountDTO.getRoleIds());
            accountRoleIds.addAll(accountDTO.getRoleIds());
            permissionGroupDTOList.add(permissionGroupDTO);
            QueryWrapper<AccountRole> accountRoleQueryWrapper = new QueryWrapper<>();
            accountRoleQueryWrapper.eq("account_id", account.getId());
            List<AccountRole> accountRoles = accountRoleService.list(accountRoleQueryWrapper);
            if(!CollectionUtils.isEmpty(accountRoles)){
                List<Integer> collect = accountRoles.stream().map(i -> i.getRoleId()).distinct().collect(Collectors.toList());
                QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
                roleQueryWrapper.in("id", collect);
                roleQueryWrapper.eq("industry_id", industryId);
                roleQueryWrapper.eq("is_deleted", false);
                List<Role> list = roleService.list(roleQueryWrapper);
                if(!CollectionUtils.isEmpty(list)){
                    List<Integer> roleIds = list.stream().map(i -> i.getId()).collect(Collectors.toList());
                    QueryWrapper<PermissionGroup> permissionGroupQueryWrapper = new QueryWrapper<>();
                    permissionGroupQueryWrapper.eq("account_id", account.getId());
                    List<PermissionGroup> list1 = permissionGroupService.list(permissionGroupQueryWrapper);
                    
                    // 保留不包含当前平台的权限组
                    for (PermissionGroup permissionGroup : list1) {
                        String roleIds1 = permissionGroup.getRoleIds();
                        List<Integer> roleIds2 = Arrays.asList(roleIds1.split(",")).stream().map(i -> Integer.valueOf(i)).collect(Collectors.toList());
                        List<Integer> old = new ArrayList<>();
                        old.addAll(roleIds2);
                        roleIds2.retainAll(roleIds);
                        // 如果为空则表示当前权限组和当前平台角色没有关系
                        if(CollectionUtils.isEmpty(roleIds2)){
                            accountRoleIds.addAll(old);
                            PermissionGroupDTO permissionGroupDTO1 = new PermissionGroupDTO();
                            permissionGroupDTO1.setAccountId(account.getId());
                            permissionGroupDTO1.setRoleList(old);
                            permissionGroupDTOList.add(permissionGroupDTO1);
                        }
                    }
                }
            }
            accountRelation.setRoleIds(accountRoleIds.stream().distinct().collect(Collectors.toList()));
            accountRelation.setCurrentIndustryId(Integer.valueOf(industryId));
            return accountService.updateAccountV2(operateAccount, account, accountRelation, permissionGroupDTOList);
        }
    }

    /**
     * 账号修改
     *
     * @param accountDTO
     * @param operateAccount
     * @return
     */
    @PostMapping(value = "/account/update")
    public ResultJson update(Account operateAccount,
                             @RequestHeader(value = "industryId", required = true) Short industryId,
                             @RequestBody AccountDTO accountDTO) {
        Account account = new Account();
        BeanUtils.copyProperties(accountDTO, account);
        account.setIndustryId(industryId);
        return accountService.updateAccount(operateAccount, account, accountDTO.getEnterpriseIds(), accountDTO.getProjectIds(), accountDTO.getRoleIds());
    }

    /**
     * 账号删除
     *
     * @param operateAccount
     * @param id
     * @return
     */
    @GetMapping(value = "/account/delete")
    public ResultJson delete(Account operateAccount,
                             @RequestHeader(value = "industryId", required = true) Short industryId,
                             @RequestParam(value = "id") Integer id) {
        return accountService.deleteAccount(operateAccount, id);
    }

    /**
     * 账号注册 APP端
     * @param accountRegisterDTO
     * @return
     */
    @PostMapping("/account/register")
    public ResultJson register(@RequestHeader(value = "appId", required = true) String appId,
                               @RequestHeader(value = "industryId", required = true) Short industryId,
                               @RequestBody AccountRegisterDTO accountRegisterDTO){
        App app = appService.getByAppId(appId);
        return accountService.register(app,industryId,accountRegisterDTO);
    }

    /**
     * 移除账号的某个角色 （关联关系）
     *
     * @param industryId
     * @param appId
     * @param accountId
     * @param roleId
     * @return
     */
    @GetMapping(value = "/account/remove-assign-role")
    public ResultJson removeAssignRole(
            Account operateAccount,
            @RequestHeader(value = "industryId", required = true) Short industryId,
            @RequestHeader(value = "appId", required = true) String appId,
            @RequestParam("accountId") Integer accountId,
            @RequestParam("roleId") Integer roleId, @RequestParam(value = "enterpriseId",required = false) Integer enterpriseId) {
        //获取当前登录操作账号的角色身份
        RoleTypeDTO operateAccountRoleType = roleService.getAccountRoleType(operateAccount.getId());
        RoleTypeEnum operateRoleType = operateAccountRoleType.getRoleTypeEnum();
        RoleTypeDTO removeAccountRoleType = roleService.getAccountRoleType(accountId);
        RoleTypeEnum removeRoleType = removeAccountRoleType.getRoleTypeEnum();
        AccountOperatorAuth accountOperatorAuth = new AccountOperatorAuth();
        accountOperatorAuth.setCurrentEnterpriseId(enterpriseId);
        accountOperatorAuth.setModifiedAccount(new Account(accountId));
        accountOperatorAuth.setOperatorAccount(operateAccount);
        Boolean checkDeleteResult = accountService.deleteAccountCheck(industryId, operateRoleType, removeRoleType, accountOperatorAuth);
        if (!checkDeleteResult) {
            return ResultJson.fail("操作者无权限移除当前账号");
        }
        return accountService.removeAssignRole(accountId, roleId);
    }

    /**
     * 批量授权
     */
    @PostMapping("/account/batch-auth")
    public ResultJson batchAuth(@RequestBody PermissionGroupDTO permissionGroupDTO,Account operateAccount){
        if (permissionGroupDTO.getStaffOrgIds().isEmpty() && permissionGroupDTO.getAccountIds().isEmpty()){
            return ResultJson.fail("参数错误");
        }
        if (!permissionGroupDTO.getStaffOrgIds().isEmpty()){
            StaffQuery staffQuery = new StaffQuery();
            staffQuery.setOrgIds(permissionGroupDTO.getStaffOrgIds());
            staffQuery.setShowCurrent(false);

            //排除企管
            Integer entId = permissionGroupDTO.getEnterpriseId();
            Map<Integer, Account> accountMap = enterpriseService.findEnterpriseAdmin(Collections.singletonList(entId));
            staffQuery.setExcludeAccountIds(Collections.singletonList(accountMap.get(entId).getId()));

            List<StaffDTO> staffDTOS = staffService.list(staffQuery);
            if (!staffDTOS.isEmpty()){
                List<Integer> accountIds = staffDTOS.stream().distinct().map(StaffDTO::getAccountId).collect(Collectors.toList());
                permissionGroupDTO.getAccountIds().addAll(accountIds);
            }
        }
        return accountService.batchAuth(permissionGroupDTO);
    }

    /**
     * 初次登录-修改个人密码
     *
     * @param accountDTO
     * @param operateAccount
     * @return
     */
    @PostMapping("/account/modify-pwd")
    public ResultJson modifyPwd(@RequestHeader String appId,
                                @RequestBody AccountDTO accountDTO, Account operateAccount, AdminAccount adminAccount) {
        String pwd = accountDTO.getPassword();
        App app = appService.getByAppId(appId);
        if (null == app) {
            return ResultJson.fail("app不存在");
        }
        if (AppTypeEnum.SYSTEM.type == app.getAppType().intValue()) {
            return adminAccountService.modifyPwd(adminAccount.getId(), pwd);
        } else {
            return accountService.modifyPwd(operateAccount.getId(), pwd);
        }
    }

//    /**
//     * 重置密码 接口暂时关闭 -华为红线要求不能提供默认密码相关接口，重置密码涉及密码
//     *
//     * @param operateAccount
//     * @param id
//     * @return
//     */
//    @GetMapping(value = "/account/reset-pwd")
//    public ResultJson resetPwd(Account operateAccount, @RequestParam("id") Integer id) {
//        return accountService.resetPwd(operateAccount.getId(), id);
//    }


    /**
     * 忘记密码-重新设置密码
     *
     * @param accountPersonalDTO
     * @return
     */
    @PostMapping(value = "/account/pwd-forgot-reset")
    public ResultJson pwdForgotReset(
            @RequestHeader(value = "appId", required = true) String appId,
            @RequestHeader(value = "clientType", required = false) Integer clientType,
            @RequestHeader(value = "industryId", required = true) Short industryId,
            @RequestBody AccountPersonalDTO accountPersonalDTO, App app) {
        if (null == accountPersonalDTO.getVerifyType()) {
            log.info("缺少设置密码类型，verifyType为空");
            return ResultJson.fail("参数异常");
        }
        String newPwd = accountPersonalDTO.getNewPwd();
        Integer verifyType = accountPersonalDTO.getVerifyType();
        ResultJson resultJson = null;
        PasswordEditEnum passwordEditEnum = PasswordEditEnum.getPasswordEditEnum(verifyType);
        String phone = null;
        String email =null;
        if (PasswordEditEnum.PHONE_VERIFY.equals(passwordEditEnum)) {
            if (StringUtils.isEmpty(accountPersonalDTO.getPhone())) {
                return ResultJson.fail("手机号不能为空");
            }
            phone = accountPersonalDTO.getPhone();
            //手机号格式校验
            CentDataVerifyUtil.phoneVerify(phone);
        }else if (PasswordEditEnum.EMAIL_VERIFY.equals(passwordEditEnum)){
            if (StringUtils.isEmpty(accountPersonalDTO.getEmail())) {
                return ResultJson.fail("邮箱不能为空");
            }
            email = accountPersonalDTO.getEmail();
            //邮箱格式校验
            CentDataVerifyUtil.emailVerify(email);
        }else {
            return ResultJson.fail("暂不支持其他方式设置密码");
        }
        //校验当前手机号是否存在关联的账号
        AbstractAccount accountDb = null;
        if (AppTypeEnum.SYSTEM.type == app.getAppType()) {
            QueryWrapper<AdminAccount> adminAccountQueryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotEmpty(phone)){
                adminAccountQueryWrapper.eq("phone", phone);
            }else {
                adminAccountQueryWrapper.eq("email", email);
            }
            adminAccountQueryWrapper.eq("is_deleted", false);
            adminAccountQueryWrapper.eq("develop_id", app.getDevelopId());
            accountDb = adminAccountService.getOne(adminAccountQueryWrapper);
        } else {
            AccountQuery accountQuery = new AccountQuery();
            if (StringUtils.isNotEmpty(phone)){
                accountQuery.setPhone(phone);
            }else {
                accountQuery.setEmail(email);
            }
            if (StringUtils.isNotEmpty(accountPersonalDTO.getDeveloperCode())) {
                Developer developer = developerService.getByCode(accountPersonalDTO.getDeveloperCode());
                if (null != developer) {
                    accountQuery.setDevelopId(developer.getId());
                }
            } else {
                // 填充默认的开发者
                accountQuery.setDevelopId(app.getDevelopId());
            }
            accountDb = accountService.getAccount(null, accountQuery);
        }
        if (null == accountDb) {
            log.info("当前手机号/邮箱未关联账号,phone={},email={},industryId={}", phone, email,industryId);
            return ResultJson.fail("此账号无效或不受支持");
        }
        if (StringUtils.isEmpty(accountPersonalDTO.getMsgCode())) {
            return ResultJson.fail("验证码不能为空");
        }
        String msgCode = accountPersonalDTO.getMsgCode();

        //验证码校验
        resultJson = messageCodeService.phoneMsgCodeVerify(String.valueOf(industryId), StringUtils.isEmpty(phone) ? email : phone, msgCode, true);
        if (!CodeEnum.SUCCESS.getCode().equals(resultJson.getCode())) {
            return resultJson;
        }

        //校验新旧密码是否相同
        if (StringUtils.isNotEmpty(accountDb.getLoginName()) && StringUtils.isNotEmpty(newPwd)) {
            if (accountDb.getLoginName().equals(newPwd)) {
                log.info("密码与用户名重复,账号id={}", accountDb.getId());
                return ResultJson.fail("密码格式错误");
            }
        }
        //密码校验
        pwdConfig.passwordCheck(newPwd);
        //修改密码
        if (AppTypeEnum.SYSTEM.type == app.getAppType()) {
            resultJson = adminAccountService.modifyPwd(accountDb.getId(), newPwd);
        } else {
            resultJson = accountService.modifyPwd(accountDb.getId(), newPwd);
        }
        return resultJson;
    }


    /**
     * 手机号or邮箱验证码校验 （不需要登录）
     *
     * @param accountPersonalDTO
     * @return
     */
    @PostMapping(value = "/account/msg-code-verify")
    public ResultJson msgCodeVerify(
            @RequestHeader(value = "appId", required = true) String appId,
            @RequestHeader(value = "clientType", required = false) Integer clientType,
            @RequestHeader(value = "industryId", required = true) Short industryId,
            @RequestBody AccountPersonalDTO accountPersonalDTO) {
        String phone = accountPersonalDTO.getPhone();
        String email = accountPersonalDTO.getEmail();
        String msgCode = accountPersonalDTO.getMsgCode();
        ResultJson resultJson = messageCodeService.phoneMsgCodeVerify(String.valueOf(industryId), StringUtils.isEmpty(phone) ? email : phone, msgCode, false);
        return resultJson;
    }

    /**
     * 密码设置校验 不能与用户名值相同
     *
     * @param resetPwdVerifyDTO
     * @return
     */
    @PostMapping(value = "/account/pwd-reset-verify")
    public ResultJson pwdResetVerify(
            @RequestHeader(value = "appId", required = true) String appId,
            @RequestHeader(value = "clientType", required = false) Integer clientType,
            @RequestHeader(value = "industryId", required = true) Short industryId,
            @RequestBody ResetPwdVerifyDTO resetPwdVerifyDTO, AdminAccount adminAccount, Developer developer) {
        if (StringUtils.isEmpty(resetPwdVerifyDTO.getRelationValue())) {
            log.info("用户账号关联值为空，无法进行密码用户名相同校验");
            return ResultJson.fail("缺少校验参数");
        }
        if (StringUtils.isEmpty(resetPwdVerifyDTO.getPassword())) {
            log.info("密码为空，无法进行密码用户名相同逻辑校验");
            return ResultJson.fail("缺少校验参数");
        }
        App app = appService.getByAppId(appId);
        if (null == app) {
            return ResultJson.fail("app不存在");
        }
        pwdConfig.passwordCheck(resetPwdVerifyDTO.getPassword());
        String relationValue = resetPwdVerifyDTO.getRelationValue();
        AbstractAccount abstractAccount = null;
        if (DataVerifyUtil.isPhoneNumber(relationValue)) {
            if (AppTypeEnum.SYSTEM.type == app.getAppType().intValue()) {// 运管平台或者开放平台后台
                QueryWrapper<AdminAccount> adminAccountQueryWrapper = new QueryWrapper<>();
                adminAccountQueryWrapper.eq("phone", relationValue);
                adminAccountQueryWrapper.eq("is_deleted", false);
                adminAccountQueryWrapper.eq("develop_id", app.getDevelopId());
                abstractAccount = adminAccountService.getOne(adminAccountQueryWrapper);
            } else {
                AccountQuery accountQuery = new AccountQuery();
//                accountQuery.setIndustryId(industryId);
                accountQuery.setDevelopId(app.getDevelopId());
                accountQuery.setPhone(relationValue);
                abstractAccount = accountService.getAccount(null, accountQuery);
            }
            if (Objects.isNull(abstractAccount)) {
                log.info("业态id={},手机号={},查找不到相关账号", industryId, relationValue);
                return ResultJson.fail("此账号无效或不受支持");
            }
            String loginName = abstractAccount.getLoginName();
            if (loginName.equals(resetPwdVerifyDTO.getPassword())) {
                return ResultJson.fail(CodeEnum.LOGIN_NAME_PWD_SAME);
            }
        } else if (DataVerifyUtil.isEmail(relationValue)) {
            if (AppTypeEnum.SYSTEM.type == app.getAppType().intValue()) {// 运管平台或者开放平台后台
                QueryWrapper<AdminAccount> adminAccountQueryWrapper = new QueryWrapper<>();
                adminAccountQueryWrapper.eq("email", relationValue);
                adminAccountQueryWrapper.eq("is_deleted", false);
                adminAccountQueryWrapper.eq("develop_id", app.getDevelopId());
                abstractAccount = adminAccountService.getOne(adminAccountQueryWrapper);
            } else {
                AccountQuery accountQuery = new AccountQuery();
                accountQuery.setIndustryId(industryId);
                accountQuery.setEmail(relationValue);
                abstractAccount = accountService.getAccount(null, accountQuery);
            }
            if (Objects.isNull(abstractAccount)) {
                log.info("业态id={},邮箱={},查找不到相关账号", industryId, relationValue);
                return ResultJson.fail("此账号无效或不受支持");
            }
            String loginName = abstractAccount.getLoginName();
            if (loginName.equals(resetPwdVerifyDTO.getPassword())) {
                return ResultJson.fail(CodeEnum.LOGIN_NAME_PWD_SAME);
            }
        } else {
            if (AppTypeEnum.SYSTEM.type == app.getAppType().intValue()) {// 运管平台或者开放平台后台
                QueryWrapper<AdminAccount> adminAccountQueryWrapper = new QueryWrapper<>();
                adminAccountQueryWrapper.eq("login_name", relationValue);
                adminAccountQueryWrapper.eq("is_deleted", false);
                adminAccountQueryWrapper.eq("develop_id", app.getDevelopId());
                abstractAccount = adminAccountService.getOne(adminAccountQueryWrapper);
            } else {
                AccountQuery accountQuery = new AccountQuery();
                accountQuery.setIndustryId(industryId);
                accountQuery.setLoginName(relationValue);
                abstractAccount = accountService.getAccount(null, accountQuery);
            }
            if (Objects.isNull(abstractAccount)) {
                log.info("业态id={},用户名={},查找不到相关账号", industryId, relationValue);
                return ResultJson.fail("此账号无效或不受支持");
            }
            String loginName = abstractAccount.getLoginName();
            if (loginName.equals(resetPwdVerifyDTO.getPassword())) {
                return ResultJson.fail(CodeEnum.LOGIN_NAME_PWD_SAME);
            }
        }
        return ResultJson.success("校验通过", true);
    }


    /**
     * 业态下手机号 是否存在
     * 这个接口在开放平台不适用，原因：开发者id从app中获取，在开放平台登录的账号都是属于不同开发者的，
     * 不能适用与在获取短信验证码时候的手机号校验，只能适用于其他平台
     *
     * @param appId
     * @param industryId
     * @param phone
     * @return
     */
    @GetMapping(value = "/account/phone-exist-check")
    public ResultJson phoneCheck(@RequestHeader(value = "appId", required = true) String appId,
                                 @RequestHeader(value = "clientType", required = false) Integer clientType,
                                 @RequestHeader(value = "industryId", required = true) Short industryId,
                                 @RequestParam(value = "phone", required = true) String phone,
                                 @RequestParam(value = "developer", required = false) String developer, App app) {
        //手机号校验
        if (!ValidatorUtil.isMobile(phone)) {
            return ResultJson.fail("手机号格式错误");
        }
        //校验当前手机号是否存在关联的账号
        AccountQuery accountQuery = new AccountQuery();
        accountQuery.setPhone(phone);
        return accountCheck(developer, accountQuery);
    }

    @GetMapping("/account/email-exist-check")
    public ResultJson emailCheck(@RequestHeader(value = "appId", required = true) String appId,
                                 @RequestHeader(value = "clientType", required = false) Integer clientType,
                                 @RequestHeader(value = "industryId", required = true) Short industryId,
                                 @RequestParam(value = "email", required = true) String email,
                                 @RequestParam(value = "developer", required = false) String developer, App app){
        if (!ValidatorUtil.isEmail(email)){
            return ResultJson.fail("邮箱格式错误");
        }
        //校验当前手机号是否存在关联的账号
        AccountQuery accountQuery = new AccountQuery();
        accountQuery.setEmail(email);
        return accountCheck(developer, accountQuery);
    }

    private ResultJson accountCheck(String developer, AccountQuery accountQuery) {
        if (StringUtils.isNotEmpty(developer)) {
            Developer de = developerService.getByCode(developer);
            if (null == de) {
                return ResultJson.fail("开发者不存在");
            } else {
                accountQuery.setDevelopId(de.getId());
            }
        } else {
            // 填充默认的开发者信息
            Developer aDefault = developerService.getDefault();
            accountQuery.setDevelopId(aDefault.getId());
        }
        Account accountDb = accountService.getAccount(null, accountQuery);
        if (null != accountDb) {
            return ResultJson.success(true);
        }
        return ResultJson.fail(CodeEnum.FAIL.code, "帐号不存在", false);
    }

    /**
     * 检查手机号是否存在 存在则进行角色关联
     * @return
     */
    @PostMapping("/account/exist-check")
    public ResultJson existCheck(@RequestBody Check check, Developer developer){
        //手机号校验
        if (!ValidatorUtil.isMobile(check.getPhone())) {
            return ResultJson.fail("手机号格式错误");
        }
        Account exist = exist(check.getPhone(), developer.getId());
        if (null != exist) {
            AccountDTO accountDTO = new AccountDTO();
            accountDTO.setName(exist.getName());
            accountDTO.setLoginName(exist.getLoginName());
            return ResultJson.fail(CodeEnum.PHONE_EXIST.code, CodeEnum.PHONE_EXIST.description, accountDTO);
        }
        return ResultJson.success();
    }

    /**
     * 存在返回true
     * @param phone
     * @param developId
     * @return
     */
    private Account exist(String phone, Integer developId){
        AccountQuery accountQuery = new AccountQuery();
        accountQuery.setPhone(phone);
        accountQuery.setDevelopId(developId);
        Account accountDb = accountService.getAccount(null, accountQuery);
        return accountDb;
    }

    /**
     * 给帐号添加角色
     * @return
     */
    @PostMapping("/account/add-role")
    public ResultJson addRole(@RequestBody AccountDTO accountDTO, Developer developer){
        //手机号校验
        if (!ValidatorUtil.isMobile(accountDTO.getPhone())) {
            return ResultJson.fail("手机号格式错误");
        }
        List<Integer> roleIds = accountDTO.getRoleIds();
        if(CollectionUtils.isEmpty(roleIds)){
            return ResultJson.fail("角色不存在");
        }
        AccountQuery accountQuery = new AccountQuery();
        accountQuery.setPhone(accountDTO.getPhone());
        accountQuery.setDevelopId(developer.getId());
        Account accountDb = accountService.getAccount(null, accountQuery);
        if(null == accountDb){
            return ResultJson.fail("帐号不存在");
        }
        return accountService.addRole(accountDb.getId(), roleIds);
    }

    /**
     * 移除运管平台角色
     * @return
     */
    @PostMapping("/account/remove-it-platform-role")
    public ResultJson removeITPlatformRole(@RequestHeader Integer industryId, @RequestBody AccountDTO accountDTO){
        if(null == accountDTO.getId()){
            return ResultJson.fail("参数错误，缺少id");
        }
        QueryWrapper<Role> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.select("id");
        roleQueryWrapper.eq("is_deleted", false);
        roleQueryWrapper.eq("industry_id", industryId);
        List<Role> list = roleService.list(roleQueryWrapper);
        if(CollectionUtils.isEmpty(list)){
            return ResultJson.fail("请先创建角色");
        }
        accountService.removeRole(accountDTO.getId(), list.stream().map(i -> i.getId()).collect(Collectors.toList()));
        return ResultJson.success();
    }

    @Data
    static class Check{

        private String phone;
    }

    /**
     * 短信验证码发送接口
     *
     * @param phone
     * @return
     */
    @GetMapping("/account/send-msg-code-open")
    public ResultJson sendMsgCodeOpen(@RequestHeader(value = "appId") String appId,
                                      @RequestHeader(value = "clientType", required = false) Integer clientType,
                                      @RequestHeader(value = "industryId", required = false) Short industryId,
                                      @RequestParam(value = "phone",required = false) String phone,
                                      @RequestParam(value = "email",required = false) String email,
                                      @RequestParam(value = "projectId", required = false) Integer projectId) {
        if (null == email && null == phone){
            return ResultJson.fail("参数错误");
        }
        if (StringUtils.isNotEmpty(email)){
            log.info("短信发送 开放接口,获取到的参数email={},projectId={}", email, projectId);
            return messageCodeService.sendEmailCode(email,projectId,String.valueOf(industryId));
        }
        log.info("短信发送 开放接口,获取到的参数phone={},projectId={}", phone, projectId);
        return messageCodeService.sendMsgCodeOpen(phone, projectId, String.valueOf(industryId));
    }


    /**
     * 设置某个账号登录状态改完已登录
     *
     * @param operateAccount
     * @return
     */
    @PostMapping("/account/set-logged")
    public ResultJson setLogged(Account operateAccount, AdminAccount adminAccount) {
        if (null != adminAccount && null != adminAccount.getId()) {
            UpdateWrapper<AdminAccount> adminAccountUpdateWrapper = new UpdateWrapper<>();
            adminAccountUpdateWrapper.eq("id", adminAccount.getId());
            adminAccountUpdateWrapper.set("is_logged", true);
            adminAccountService.update(adminAccountUpdateWrapper);
            return ResultJson.success();
        } else {
            return accountService.setLogged(operateAccount.getId());
        }
    }

    /**
     * 验重 业态下 登录名 或者 手机号 或者 邮箱
     *
     * @param appId
     * @param industryId
     * @param id
     * @param loginName
     * @param phone
     * @return
     */
    @RequestMapping(value = "/account/exist-check", method = RequestMethod.GET)
    public ResultJson accountDataExistChecking(@RequestHeader(value = "appId", required = true) String appId,
                                               @RequestHeader(value = "industryId", required = true) Short industryId,
                                               @RequestParam(value = "id", required = false) Integer id,
                                               @RequestParam(value = "loginName", required = false) String loginName,
                                               @RequestParam(value = "email", required = false) String email,
                                               @RequestParam(value = "phone", required = false) String phone,
                                               @RequestParam(value = "idCard",required = false) String idCard, Developer developer) {
        if (StringUtils.isEmpty(loginName) && StringUtils.isEmpty(phone) && StringUtils.isEmpty(email) &&StringUtils.isEmpty(idCard)) {
            log.info("账号验重数据异常，获取到的登录名 和 手机号 和 邮箱 和 身份证 都为空");
            return ResultJson.fail("缺少需校验数据");
        }
        if (null == developer || null == developer.getId()) {
            return ResultJson.fail("缺少开发者信息");
        }
        if (StringUtils.isNotEmpty(loginName)) {
            CentDataVerifyUtil.loginNameVerify(loginName);
        }
        if (StringUtils.isNotEmpty(phone)) {
            CentDataVerifyUtil.phoneVerify(phone);
        }
        if (StringUtils.isNotEmpty(email)) {
            CentDataVerifyUtil.emailVerify(email);
        }
        if (StringUtils.isNotEmpty(idCard)){
            if (!com.xhwl.common.utils.ValidatorUtil.isIDCard(idCard)){
                throw new DataException("身份证号格式不正确");
            }
        }
        Account account = new Account();
        account.setIndustryId(industryId);
        account.setLoginName(loginName);
        account.setPhone(phone);
        account.setEmail(email);
        account.setIdCard(idCard);
        account.setId(id);
        account.setDevelopId(developer.getId());
        accountService.accountUnique(account);
        return ResultJson.success("验证通过");
    }

    /**
     * 验重 业态下 登录名 或者 手机号 或者 邮箱
     *
     * @param appId
     * @param industryId
     * @param id
     * @param loginName
     * @param phone
     * @return
     */
    @RequestMapping(value = "/account/exist-check/v2", method = RequestMethod.GET)
    public ResultJson accountDataExistCheck(@RequestHeader(value = "appId", required = true) String appId,
                                            @RequestHeader(value = "industryId", required = true) Short industryId,
                                            @RequestParam(value = "id", required = false) Integer id,
                                            @RequestParam(value = "loginName", required = false) String loginName,
                                            @RequestParam(value = "email", required = false) String email,
                                            @RequestParam(value = "phone", required = false) String phone, Developer developer) {
        if (StringUtils.isEmpty(loginName) && StringUtils.isEmpty(phone) && StringUtils.isEmpty(email)) {
            log.info("账号验重数据异常，获取到的登录名 和 手机号 和 邮箱 都为空");
            return ResultJson.fail("缺少需校验数据");
        }
        if (StringUtils.isNotEmpty(loginName)) {
            CentDataVerifyUtil.loginNameVerify(loginName);
        }
        if (StringUtils.isNotEmpty(phone)) {
            CentDataVerifyUtil.phoneVerify(phone);
        }
        if (StringUtils.isNotEmpty(email)) {
            CentDataVerifyUtil.emailVerify(email);
        }
        Account account = new Account();
        account.setIndustryId(industryId);
        account.setLoginName(loginName);
        account.setPhone(phone);
        account.setEmail(email);
        account.setId(id);
        accountService.accountUnique(account);
        return ResultJson.success("验证通过");
    }


    /**
     * 获取当前账号的关联角色信息
     *
     * @param appId
     * @param industryId
     * @param id
     * @return
     */
    @RequestMapping(value = "/account/get-roles", method = RequestMethod.GET)
    public ResultJson getRolesInfo(@RequestHeader(value = "appId", required = true) String appId,
                                   @RequestHeader(value = "industryId", required = true) Short industryId,
                                   @RequestParam(value = "id", required = true) Integer id,
                                   @RequestParam(value = "projectId", required = false) Integer projectId,
                                   @RequestParam(value = "enterpriseId", required = false) Integer enterpriseId) {
        List<AccountRolesDTO> accountRoles = accountService.getAccountRoles(id);
        if (ChkUtil.isNotNull(projectId) && ChkUtil.isNotNull(accountRoles)) {
            accountRoles = accountRoles.stream().filter((e) -> projectId.equals(e.getProjectId())).collect(Collectors.toList());
        }
        // 过滤掉非当前查询企业
        if (ChkUtil.isNotNull(enterpriseId) && ChkUtil.isNotNull(accountRoles)) {
            Enterprise enterprise = enterpriseService.findById(enterpriseId);
            if (null != enterprise) {
                accountRoles = accountRoles.stream().filter((e) -> null != e.getOrgStructureName() && e.getOrgStructureName().equals(enterprise.getName())).collect(Collectors.toList());
            }
        }
        return ResultJson.success(accountRoles);
    }


    /**
     * 获取当前账号的关联项目信息
     *
     * @param appId
     * @param industryId
     * @param id
     * @return
     */
    @RequestMapping(value = "/account/get-projects", method = RequestMethod.GET)
    public ResultJson getProjectInfo(@RequestHeader(value = "appId", required = true) String appId,
                                     @RequestHeader(value = "industryId", required = true) Short industryId,
                                     @RequestParam(value = "id", required = true) Integer id) {
        List<AccountProjectsDTO> accountRoles = accountService.getAccountProjects(id);
        return ResultJson.success(accountRoles);
    }

    /**
     * 修改状态
     *
     * @param accountDTO
     * @param operator
     * @return
     */
    @PostMapping(value = "/account/set-status")
    public ResultJson setStatus(@RequestBody AccountDTO accountDTO, Account operator) {
        if (null == accountDTO.getId()) {
            return ResultJson.fail("id 错误");
        }
        if (null == accountDTO.getStatus()) {
            return ResultJson.fail("status 错误");
        }
        Account account = accountService.findById(accountDTO.getId());
        if (null == account) {
            return ResultJson.fail("账号不存在");
        }
        account.setStatus(accountDTO.getStatus());
        return accountService.updateAccount(operator, account);
    }

    @PostMapping(value = "/account/batch-set-status")
    public ResultJson batchSetStatus(@RequestBody AccountDTO accountDTO, Account operator) {

        if (CollectionUtils.isEmpty(accountDTO.getIds())) {
            return ResultJson.fail("参数错误");
        }
        if (null == accountDTO.getStatus()) {
            return ResultJson.fail("状态参数错误");
        }
        UpdateWrapper<Account> accountUpdateWrapper = new UpdateWrapper<>();
        accountUpdateWrapper.in("id", accountDTO.getIds());
        accountUpdateWrapper.set("status", accountDTO.getStatus());
        accountService.update(accountUpdateWrapper);
        return ResultJson.success();
    }

    @RequestMapping(value = "/account/find-higherup", method = RequestMethod.GET)
    public ResultJson findHigherUp(@RequestParam(value = "loginName", required = true) String loginName,
                                   @RequestParam(value = "grade",required = true)Integer grade,
                                   @RequestParam(value = "enterpriseId",required = true) Integer enterpriseId,
                                   @RequestParam(value = "developId",required = false) Integer developId){
        if (null == developId){
            developId = developerService.getDefault().getId();
        }
        return accountService.findHigherUp(loginName,grade,developId,enterpriseId);
    }

    @RequestMapping(value = "/account/find-managers", method = RequestMethod.GET)
    public ResultJson managersByAccountId(@RequestParam(value = "loginName", required = true) String loginName,
                                          @RequestParam(value = "enterpriseId",required = true) Integer enterpriseId,
                                          @RequestParam(value = "developId",required = false) Integer developId){
        if (null == developId){
            developId = developerService.getDefault().getId();
        }
        return accountService.managersByAccountId(loginName,developId,enterpriseId);
    }
    @GetMapping(value = "/account/find-enterprise")
    public ResultJson findEnterprise(Account account){
        if (null == account){
            return ResultJson.fail("参数错误");
        }
        return ResultJson.success(enterpriseService.findByAccount(account));
    }

    @RequestMapping(value = "/account/check-account", method = RequestMethod.GET)
    public ResultJson checkAccount(@RequestHeader(value = "appId",required = true) String appId,
                                   @RequestParam(value = "loginNames", required = true) List<String> loginNames){

        App app = appService.getByAppId(appId);
        if (app == null){
            return ResultJson.fail("参数错误");
        }
        return accountService.checkAccount(loginNames,app.getDevelopId());
    }

    /**
     * 根据账号id查询关联类型空间路址
     *
     * @return
     */
    @GetMapping(value = "/account/find-space")
    public ResultJson findSpace(Account account, String typeCode) {
        if (null == account) {
            return ResultJson.fail("参数错误");
        }
        return ResultJson.success(buildingService.findSpace(account, typeCode));
    }

    /**
     * 获取当前密码模式
     * @return
     */
    @GetMapping("/account/pwd/model")
    public ResultJson pwdModel(){
        return ResultJson.success("操作成功", pwdConfig.getModel());
    }

    @PostMapping("/account/get-dual-auth")
    public ResultJson getDualAuth(@RequestBody AuthenticationDTO authenticationDTO, Account account, App app){
        Account accountDB = null;
        if(StringUtils.isEmpty(authenticationDTO.getLoginName())){
            if(null == account){
                return ResultJson.fail("参数错误");
            }
            accountDB = accountService.findById(account.getId());
        }else{
            accountDB = getAccountByLoginKey(authenticationDTO.getLoginName(), app);
        }
        return ResultJson.success(null == accountDB || null == accountDB.getDualAuth() ? false : accountDB.getDualAuth());
    }

    private Account getAccountByLoginKey(String loginName, App app){
        if (DataVerifyUtil.isPhoneNumber(loginName)) {
            QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
            accountQueryWrapper.eq("phone", loginName);
            accountQueryWrapper.eq("develop_id", app.getDevelopId());
            accountQueryWrapper.eq("is_deleted", false);
            return accountService.getOne(accountQueryWrapper);
        } else if (DataVerifyUtil.isEmail(loginName)) {
            QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
            accountQueryWrapper.eq("email", loginName);
            accountQueryWrapper.eq("develop_id", app.getDevelopId());
            accountQueryWrapper.eq("is_deleted", false);
            return accountService.getOne(accountQueryWrapper);
        } else{
            return accountService.findByLoginNameV2(loginName, app.getDevelopId());
        }
    }

    @PostMapping("/account/set-dual-auth")
    public ResultJson setDualAuth(@RequestBody AuthenticationDTO authenticationDTO, Account account){
        if(null == authenticationDTO.getDualAuth()){
            return ResultJson.fail("参数错误");
        }
        UpdateWrapper<Account> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", account.getId());
        updateWrapper.set("dual_auth", authenticationDTO.getDualAuth());
        accountService.update(updateWrapper);
        return ResultJson.success();
    }

    /**
     * 查询项目开关状态（开或关闭）
     */

    @GetMapping("/account/get-show-project")
    public ResultJson getShowProject(Account account){
        Account accountDB = null;
        if(null == account){
            return ResultJson.fail("登录过期,请重新登录或尝试刷新");
        }
        accountDB = accountService.findById(account.getId());
        return ResultJson.success(null == accountDB || null == accountDB.getShowProject() ? true : accountDB.getShowProject());
    }

    /**
     * 项目选择设置（开或关闭）
     */
    @PostMapping("/account/set-show-project")
    public ResultJson setShowProject(@RequestParam Boolean switchProject, Account account){
        if(null == switchProject){
            return ResultJson.fail("参数错误");
        }
        UpdateWrapper<Account> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", account.getId());
        updateWrapper.set("show_project", switchProject);
        accountService.update(updateWrapper);
        return ResultJson.success();
    }
    /**
     * 登录的项目配置
     */
    @PostMapping("/account/account-set-login-project")
    public ResultJson setLoginProject(@RequestBody AccountDTO accountDTO,Account account){
        if (null == accountDTO.getDefaultEnterprise() || null == accountDTO.getDefaultProject()){
            return ResultJson.fail("缺少企业或项目信息");
        }
        UpdateWrapper<Account> updateWrapper = new UpdateWrapper();
        updateWrapper.eq("id", account.getId());
        updateWrapper.set("default_project", accountDTO.getDefaultProject());
        updateWrapper.set("default_enterprise", accountDTO.getDefaultEnterprise());
        accountService.update(updateWrapper);
        return ResultJson.success();
    }

    /**
     * 登录的项目配置查询
     */
    @GetMapping("/account/account-get-login-project")
    public ResultJson getLoginProject(Account account){
        QueryWrapper<Account> accountQueryWrapper = new QueryWrapper<>();
        accountQueryWrapper.eq("id",account.getId());
        List<Account> list = accountService.list(accountQueryWrapper);
        if (list.size() == 0){
            return ResultJson.fail("账号信息不存在");
        }else {
            return ResultJson.success(list.get(0));
        }
    }

    /**
     * 当登录账号只有1个项目权限时，系统自动跳过该页面，自动选中项目直接进入首页
     */
    @PostMapping("/account/account-one-project")
    public ResultJson accountOneProject(@RequestBody EnterpriseQuery enterpriseQuery, Account account){
        if (null == account || null == account.getId()) {
            return ResultJson.fail("缺少帐号信息");
        }
        List<Enterprise> enterprises = enterpriseService.list(enterpriseQuery, account);
        Integer defaultEnterprise = accountService.getById(account.getId()).getDefaultEnterprise();
        for (Enterprise enterprise : enterprises) {
            if (null != defaultEnterprise && enterprise.getId().equals(defaultEnterprise)){
                enterprise.setSelectedEnterprise(true);
            }
            OrganizationQuery organizationQuery = new OrganizationQuery();
            organizationQuery.setEnterpriseId(enterprise.getId());
            organizationQuery.setAccountId(account.getId());
            List<Project> projects = organizationService.projectChoseV3(organizationQuery, account);
            if (projects.size() == 1){
                ResultJson loginProject = getLoginProject(account);
                //如果默认项目空，则需要设置默认项目
                if (null == loginProject.getResult() || "".equals(loginProject.getResult())){
                    UpdateWrapper<Account> updateWrapper = new UpdateWrapper();
                    updateWrapper.eq("id", account.getId());
                    updateWrapper.set("show_project", projects.get(0).getId());
                    updateWrapper.set("default_enterprise", enterprise.getId());
                    accountService.update(updateWrapper);
                }
                return ResultJson.success(true);
            }
            //默认企业未查询出的第一个企业，第一次循环就结束判断
            break;
        }
        return ResultJson.success(false);

    }

    /**
     * 动态查询账号list Query条件填充
     *
     * @param industryId
     * @param accountSearch
     * @param operateAccount
     * @return
     */
    public AccountQuery convertDynamicAccountQuery(Short industryId, AccountSearchVO accountSearch, Account operateAccount) {
        boolean needAuth = true;
        if (Objects.nonNull(accountSearch.getNeedAuth())) {
            needAuth = accountSearch.getNeedAuth();
        }
        List<Integer> enterpriseIds = accountSearch.getEntIds();
        List<Integer> projectIds = accountSearch.getProIds();
        //获取当前登录操作账号的角色身份
        RoleTypeDTO accountRoleType = roleService.getAccountRoleType(operateAccount.getId());
        RoleTypeEnum operateRoleType = accountRoleType.getRoleTypeEnum();
        //默认根据企业首字母顺序排列
        //账号列表动态查询条件
        AccountQuery accountQuery = new AccountQuery();
//        accountQuery.setIndustryId(industryId);
        accountQuery.setOperateRoleType(operateRoleType);
        accountQuery.setNeedProjectPerson(accountSearch.getNeedProjectPerson());
        //needAuth  与当前操作账号做权限交集
        if (needAuth) {
            //超管
            if (RoleTypeEnum.SUPPER_MANAGER.getCode() == operateRoleType.getCode()) {
                //额外查看超管账号
                fillSuperAdminIds(accountSearch, accountQuery);
                EnterpriseQuery enterpriseQuery = new EnterpriseQuery();
                enterpriseQuery.setIndustryIdList(Arrays.asList(industryId));
                List<Enterprise> enterprisesDb = enterpriseService.list(enterpriseQuery, null);
                //设置查询的企业ids
                if (!CollectionUtils.isEmpty(enterprisesDb)) {
                    List<Integer> enterpriseIdListDb = enterprisesDb.stream().map(Enterprise::getId).collect(Collectors.toList());
                    enterpriseIds = entIdsCrossDeal(enterpriseIds, enterpriseIdListDb);
                }
            } else if (RoleTypeEnum.ENT_MANAGER.getCode() == operateRoleType.getCode()) {
                //企管 只能查看自己企业id的账号
                List<Integer> enterpriseIdListDb = accountRoleType.getEnterpriseIdList();
                //设置查询的企业ids
                if (!CollectionUtils.isEmpty(enterpriseIdListDb)) {
                    enterpriseIds = entIdsCrossDeal(enterpriseIds, enterpriseIdListDb);
                }
            } else if (RoleTypeEnum.PRO_MANAGER.getCode() == operateRoleType.getCode()) {
                List<Integer> projectIdList = accountRoleType.getProjectIdList();
                //将项目所属的企业获取出来
                ProjectQuery projectQuery = new ProjectQuery();
                projectQuery.withIdList(projectIdList);
                List<Project> projects = projectService.list(projectQuery, null);
                if (!CollectionUtils.isEmpty(projects)) {
                    //设置查询的项目ids
                    List<Integer> projectIdListDb = projects.stream().map(Project::getId).collect(Collectors.toList());
                    projectIds = proIdsCrossDeal(projectIds, projectIdListDb);
                    //设置查询的企业ids
                    List<Integer> enterpriseIdListDb = projects.stream().map(Project::getEnterpriseId).collect(Collectors.toList());
                    enterpriseIds = entIdsCrossDeal(enterpriseIds, enterpriseIdListDb);
                }
                //设置项目管理员可查看的账号id
                List<Integer> accountIdList = proAdminCanSearchSetting(operateAccount);
                accountQuery.setIdList(accountIdList);
            }

        }
        if (!CollectionUtils.isEmpty(enterpriseIds)) {
            accountQuery.setEnterpriseIdList(enterpriseIds);
        }
        if (!CollectionUtils.isEmpty(projectIds)) {
            accountQuery.setProjectIdList(projectIds);
        }
        accountQuery.setOrganizationIds(accountSearch.getOrganizationIds());
        accountQuery.setCurrentOrganization(accountSearch.isCurrentOrganization());
        searchSetting(accountSearch, accountQuery);

        //如果不包含游客角色类型
        if (!accountSearch.getNeedIncludeTourist()) {
            List<Role> touristRoleByIndustryId = roleService.getTouristRoleByIndustryId(industryId);
            if (!CollectionUtils.isEmpty(touristRoleByIndustryId)) {
                List<Integer> collect = touristRoleByIndustryId.stream().map(role -> role.getId()).collect(Collectors.toList());
                List<Integer> excludeRoleIdList = accountQuery.getExcludeRoleIdList();
                if (excludeRoleIdList == null) {
                    excludeRoleIdList = new ArrayList<>();
                }
                excludeRoleIdList.addAll(collect);
                accountQuery.setExcludeRoleIdList(excludeRoleIdList);
            }
        }
        return accountQuery;
    }


    /**
     * 搜索条件设置
     *
     * @param accountSearch
     * @param accountQuery
     */
    public void searchSetting(AccountSearchVO accountSearch, AccountQuery accountQuery) {
        if (!CollectionUtils.isEmpty(accountSearch.getRoleIds())) {
            accountQuery.setRoleIdList(accountSearch.getRoleIds());
        }
        if (StringUtils.isNotEmpty(accountSearch.getLikeSearch())) {
            accountQuery.setLikeSearch(accountSearch.getLikeSearch());
        }
        if (StringUtils.isNotEmpty(accountSearch.getLikeNameOrPhone())) {
            accountQuery.setLikeNameOrPhone(accountSearch.getLikeNameOrPhone());
        }
        if (StringUtils.isNotEmpty(accountSearch.getLikeRoleName())) {
            accountQuery.setLikeRoleName(accountSearch.getLikeRoleName());
        }
        if (StringUtils.isNotEmpty(accountSearch.getLikeLoginName())) {
            accountQuery.setLikeLoginName(accountSearch.getLikeLoginName());
        }
        if (StringUtils.isNotEmpty(accountSearch.getLikeName())) {
            accountQuery.setLikeName(accountSearch.getLikeName());
        }
        if (!CollectionUtils.isEmpty(accountSearch.getAccountIds())) {
            accountQuery.setIdList(accountSearch.getAccountIds());
        }

        if (null != accountSearch.getNeedCommonInitialized()) {
            accountQuery.setNeedCommonInitialized(accountSearch.getNeedCommonInitialized());
        }


    }

    /**
     * 企业id取交集
     *
     * @param enterpriseIds
     * @param enterpriseIdListDb
     * @return
     */
    public List<Integer> entIdsCrossDeal(List<Integer> enterpriseIds, List<Integer> enterpriseIdListDb) {
        if (!CollectionUtils.isEmpty(enterpriseIdListDb)) {
            //企业id 与 传入的企业id取交集
            if (!CollectionUtils.isEmpty(enterpriseIds)) {
                List<Integer> entIdsResult = enterpriseIdListDb.stream().filter(enterpriseIds::contains).collect(Collectors.toList());
                enterpriseIds = entIdsResult;
            } else {
                enterpriseIds = new ArrayList<>(enterpriseIdListDb);
            }
        }
        return enterpriseIds;
    }

    /**
     * 项目id取交集
     *
     * @param projectIds
     * @param projectIdListDb
     * @return
     */
    public List<Integer> proIdsCrossDeal(List<Integer> projectIds, List<Integer> projectIdListDb) {
        if (!CollectionUtils.isEmpty(projectIdListDb)) {
            //企业id 与 传入的企业id取交集
            if (!CollectionUtils.isEmpty(projectIds)) {
                List<Integer> entIdsResult = projectIdListDb.stream().filter(projectIds::contains).collect(Collectors.toList());
                projectIds = entIdsResult;
            } else {
                projectIds = new ArrayList<>(projectIdListDb);
            }
        }
        return projectIds;
    }


    /**
     * 项目管理员功能权限过滤 （只能查看项管和普通账号）
     *
     * @param operateAccount
     * @return
     */
    public List<Integer> proAdminCanSearchSetting(Account operateAccount) {
        List<Role> roleList = roleService.getRoleList(operateAccount, null);
        List<Integer> roleIdList = roleList.stream().map(Role::getId).collect(Collectors.toList());
        List<Integer> accountIdList = accountRoleService.findByRoleId(roleIdList);
        Set<Integer> accountIdSet = new HashSet<>(accountIdList);
        accountIdList = new ArrayList<>(accountIdSet);
        //去除超管 、去除企管
        accountIdList = removeSuperAdminAccount(accountIdList);
        accountIdList = removeEntAdminAccount(accountIdList);
        return accountIdList;
    }

    /**
     * 填充超管账号（超管能查看超管）
     *
     * @param accountSearch
     * @param accountQuery
     */
    public void fillSuperAdminIds(AccountSearchVO accountSearch, AccountQuery accountQuery) {
        RoleQuery roleQuery = new RoleQuery();
        roleQuery.setIndustryIdList(Arrays.asList(accountQuery.getIndustryId()));
        roleQuery.setGrade(BusinessType.INDUSTRY.getCode());
        roleQuery.setType(RoleTypeEnum.SUPPER_MANAGER.getCode());
        List<Role> superManagerRoleList = roleService.getRoleList(null, roleQuery);
        if (!CollectionUtils.isEmpty(superManagerRoleList)) {
            List<Integer> superManagerRoleIds = superManagerRoleList.stream().map(Role::getId).collect(Collectors.toList());
            List<Integer> superManagerAccountIds = accountRoleService.findByRoleId(superManagerRoleIds);
            //如果不根据企业、项目筛选，需要额外查询出超管账号
            if (CollectionUtils.isEmpty(accountSearch.getEntIds()) && CollectionUtils.isEmpty(accountSearch.getProIds())) {
                accountQuery.setOrSuperManagerIds(superManagerAccountIds);
            }
        }
    }


    /**
     * 移除超管账号
     *
     * @param accountIdList
     * @return
     */
    public List<Integer> removeSuperAdminAccount(List<Integer> accountIdList) {
        List<Integer> accountIds = accountService.getAdminAccountDynamic(RoleTypeEnum.SUPPER_MANAGER.getCode(), BusinessType.INDUSTRY.getCode(), accountIdList);
        List<Integer> resultList = new ArrayList<>();
        if (CollectionUtils.isEmpty(accountIds)) {
            resultList.addAll(accountIdList);
        } else {
            for (Integer id : accountIdList) {
                if (!accountIds.contains(id)) {
                    resultList.add(id);
                }
            }
        }
        return resultList;
    }

    /**
     * 移除企管账号
     *
     * @param accountIdList
     * @return
     */
    public List<Integer> removeEntAdminAccount(List<Integer> accountIdList) {
        List<Integer> accountIds = accountService.getAdminAccountDynamic(RoleTypeEnum.MANAGER.getCode(), BusinessType.ENTERPRISE.getCode(), accountIdList);
        List<Integer> resultList = new ArrayList<>();
        if (CollectionUtils.isEmpty(accountIds)) {
            resultList.addAll(accountIdList);
        } else {
            for (Integer id : accountIdList) {
                if (!accountIds.contains(id)) {
                    resultList.add(id);
                }
            }
        }
        return resultList;
    }


    /**
     * 设置搜索默认条件
     *
     * @param page
     */
    public void setDefaultSearchOrder(Page page) {
        if (null == page.getOrders() || page.getOrders().isEmpty()) {
            List<OrderItem> order = new ArrayList<>(1);
            OrderItem item = new OrderItem();
            item.setColumn("CONVERT( enterpriseName USING gbk ) COLLATE gbk_chinese_ci");
            order.add(item);
            OrderItem itemId = new OrderItem();
            itemId.setColumn("id");
            itemId.setAsc(false);
            order.add(itemId);
            page.setOrders(order);
        }
    }


}
